#!/usr/bin/env bash

set -o errexit
set -o pipefail

DC="${DC:-exec}"

# If we're running in CI we need to disable TTY allocation for docker compose
# commands that enable it by default, such as exec and run.
TTY=""
if [[ ! -t 1 ]]; then
  TTY="-T"
fi

# -----------------------------------------------------------------------------
# Helper functions start with _ and aren't listed in this script's help menu.
# -----------------------------------------------------------------------------

function _dc {
  docker compose "${DC}" ${TTY} "${@}"
}

function _build_run_down {
  docker compose build
  docker compose run ${TTY} "${@}"
  docker compose down
}

# -----------------------------------------------------------------------------

function cmd {
  # Run any command you want in the web container
  _dc web "${@}"
}

function flask {
  # Run any Flask commands
  cmd flask "${@}"
}

function lint:dockerfile {
  # Lint Dockerfile
  docker container run --rm -i \
    hadolint/hadolint hadolint --ignore DL3008 -t style "${@}" - < Dockerfile
}

function lint {
  # Lint Python code
  cmd flake8 "${@}"
}

function format:imports {
  # Sort Python imports
  cmd isort . "${@}"
}

function format {
  # Format Python code
  cmd black . "${@}"
}

function quality {
  # Perform all code quality commands together
  format:imports "${@}"
  format "${@}"
  lint "${@}"
}

function test {
  # Run test suite
  cmd pytest test/ "${@}"
}

function test:coverage {
  # Get test coverage
  cmd pytest --cov snakeeyes/ --cov lib/ --cov-report term-missing "${@}"
}

function shell {
  # Start a Shell session in the web container
  cmd bash "${@}"
}

function redis-cli {
  # Connect to Redis with redis-cli
  _dc redis redis-cli "${@}"
}

function pip3:install {
  # Install pip3 dependencies and write lock file
  _build_run_down web bin/pip3-install
}

function pip3:outdated {
  # List any installed packages that are outdated
  cmd pip3 list --outdated
}

function yarn:install {
  # Install yarn dependencies and write lock file
  _build_run_down webpack yarn install
}

function yarn:outdated {
  # List any installed packages that are outdated
  _dc webpack yarn outdated
}

function clean {
  # Remove cache and other machine generates files
  rm -rf .pytest_cache/ .webpack_cache/ public/* .coverage celerybeat-schedule
  touch public/.keep
}

function help {
  printf "%s <task> [args]\n\nTasks:\n" "${0}"

  compgen -A function | grep -v "^_" | cat -n

  printf "\nExtended help:\n  Each task has comments for general usage\n"
}

# This idea is heavily inspired by: https://github.com/adriancooney/Taskfile
TIMEFORMAT=$'\nTask completed in %3lR'
time "${@:-help}"
